package org.test.jiazi_1.common.utils;

import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.write.handler.context.CellWriteHandlerContext;
import cn.idev.excel.write.metadata.style.WriteCellStyle;
import cn.idev.excel.write.metadata.style.WriteFont;
import cn.idev.excel.write.style.AbstractVerticalCellStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.DefaultIndexedColorMap;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;

import java.util.Objects;

/**
 * @Author: 唐文涛
 * @CreateTime: 2024-11-27
 * @Description:
 * @Version: 1.0
 */
public class ReportExportCellWriteHandler extends AbstractVerticalCellStyleStrategy {
    @Override
    protected void setHeadCellStyle(CellWriteHandlerContext context) {
        // 获取和创建CellStyle
        WriteCellData<?> cellData = context.getFirstCellData();
        CellStyle originCellStyle = cellData.getOriginCellStyle();
        Cell cell = context.getCell();
        cell.setCellStyle(originCellStyle);

        if (Objects.isNull(originCellStyle)) {
            originCellStyle = context.getWriteWorkbookHolder().getWorkbook().createCellStyle();
        }

        // 设置背景颜色
        ((XSSFCellStyle) originCellStyle).setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 255, 255),
                new DefaultIndexedColorMap()));


        // 设置背景颜色
        originCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 重点！！！ 由于在FillStyleCellWriteHandler，会把OriginCellStyle和WriteCellStyle合并，会已WriteCellStyle
        // 样式为主，所有必须把WriteCellStyle设置的背景色清空
        // 具体合并规则请看WriteWorkbookHolder.createCellStyle方法
        WriteCellStyle writeCellStyle = cellData.getWriteCellStyle();
        writeCellStyle.setFillForegroundColor(null);
        // 重点！！！ 必须设置OriginCellStyle
        cellData.setOriginCellStyle(originCellStyle);

        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteFont.setFontName("Arial");
        headWriteFont.setBold(false);

        // 设置列宽
        context.getWriteSheetHolder().getSheet().setColumnWidth(0, 20 * 256);
        // 设置行高
        Row row = context.getRow();
        row.setHeightInPoints(25); // 设置行高为25点

        cellData.getWriteCellStyle().setWriteFont(headWriteFont);
    }
}